<template>
  <a-form-model ref="form_" :model="skuModel" :rules="validatorRules_" slot="detail">
    <div class="sku-title">SKU</div>
    <a-row>
      <a-col :span="24">
        <a-form-model-item label="颜色" :labelCol="labelCol" :wrapperCol="{xs: { span: 24 }, sm: { span: 24 }}" prop="color">
          <a-checkbox-group class="color-setting" v-model="skuModel.color" >
            <a-checkbox :value="item.id" v-for="(item, index) in colorList" :key="item.id">
              <span class="color" :style="{ background: item.value }"></span>
              <span class="text">{{ item.title }}</span>
            </a-checkbox>
          </a-checkbox-group>
        </a-form-model-item>
      </a-col>
      <a-col :span="24">
        <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="{xs: { span: 24 }, sm: { span: 5 }}" prop="colorName">
          <a-input v-model.trim="skuModel.colorName" placeholder="自定义颜色:例如：红色,黄色" ></a-input>
        </a-form-model-item>
      </a-col>
      <a-col :span="24">
        <a-form-model-item label="尺寸" :labelCol="labelCol" :wrapperCol="{xs: { span: 24 }, sm: { span: 24 }}" prop="size">
          <div>
            <div :span="24" v-for="(item, index) in sizeList" :key="index">
              <span style="display: inline-block; width: 80px;">{{ item.name }}:</span>
              <a-checkbox-group v-model="skuModel.size" @change="handleChange(3)">
                <a-checkbox :value="itemChild.title" v-for="(itemChild, indexChild) in item.attributeList" :key="indexChild">{{ itemChild.title }}</a-checkbox>
              </a-checkbox-group>
            </div>
          </div>
        </a-form-model-item>
      </a-col>
      <a-col :span="24">
        <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="{xs: { span: 24 }, sm: { span: 5 }}" prop="sizeName">
          <a-input v-model.trim="skuModel.sizeName" placeholder="请输入尺寸(重大到小) 例如：M,S,XS" @change="handleChange(4)" ></a-input>
        </a-form-model-item>
      </a-col>
      <a-button type="danger" @click="handleGenerate" style="margin-bottom: 20px;" v-if="!originModel.productType">生成SKU</a-button>
      <a-col :span="24">
        <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="{xs: { span: 24 }, sm: { span: 24 }}" :validate-status="skuValid.validateStatus" :help="skuValid.message">
          <j-vxe-table
            :disabled="originModel.productType ? true : false"
            v-if="table.dataSource && table.dataSource.length"
            style="margin-top: 20px;"
            class="j-vxe-table j-vxe-table-custom"
            ref="vTable"
            :loading="table.loading"
            :columns="table.columns"
            :dataSource="table.dataSource"
            :pagination="null"
          >
            <template v-slot:action="props" v-if="!originModel.productType">
              <a-popconfirm title="确定删除吗？" @confirm="handleDL(props)">
                <a>删除</a>
              </a-popconfirm>
            </template>
          </j-vxe-table>
        </a-form-model-item>
      </a-col>
    </a-row>
  </a-form-model>
</template>

<script>
import { postAction, getAction } from '@/api/manage'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
export default {
  name: 'Sku',
  props: {
    model: {
      type: Object,
      default: () => {}
    },
    originModel: {
      type: Object,
      default: () => {}
    }
  },
  data(){
    return {
      skuModel: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      colorList: [],
      sizeList: {},
      skuValid: {
        validateStatus: '',
        message: ''
      },
      validatorRules_: {
        color: [
          { validator: this.colorValidator }
        ],
        size: [
          { validator: this.sizeValidator }
        ],
        colorName: [
          { required: false, message: '请使用英文逗号分隔!', pattern: /^[\u4e00-\u9fff0-9a-zA-Z,]+$/}
        ],
        sizeName: [
          { required: false, message: '请使用英文逗号分隔!', pattern: /^[\u4e00-\u9fff0-9a-zA-Z,]+$/}
        ]
      },
      table: {
        // 是否正在加载
        loading: false,
        // 分页器参数
        pagination: {
          // 当前页码
          current: 1,
          // 每页的条数
          pageSize: 20,
          // 可切换的条数
          pageSizeOptions: ['10', '20', '30', '100', '200'],
          // 数据总数（目前并不知道真实的总数，所以先填写0，在后台查出来后再赋值）
          total: 0,
        },
        // 最后选中的行
        lastRow: null,
        // 选择的行
        selectedRows: [],
        // 数据源，控制表格的数据
        dataSource: [],
        // 列配置，控制表格显示的列
        columns: [
          {
            title: 'SKU',
            key: 'skuCode',
            type: JVXETypes.input,
            width: '200px',
            defaultValue: '',
            placeholder: '请输入${title}',
            disabled: true,
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}' // 显示的文本
              }
            ]
          },
          {
            title: '产品名称',
            key: 'name',
            type: JVXETypes.input,
            width: '200px',
            defaultValue: '',
            placeholder: '请输入${title}',
            disabled: true,
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}' // 显示的文本
              }
            ]
          },
          {
            title: '颜色',
            key: 'color_',
            type: JVXETypes.input,
            width: '100px',
            defaultValue: '',
            placeholder: '请输入${title}',
            disabled: true,
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}' // 显示的文本
              }
            ]
          },
          {
            title: '尺寸',
            key: 'size',
            type: JVXETypes.input,
            width: '100px',
            defaultValue: '',
            placeholder: '请输入${title}',
            disabled: true,
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}' // 显示的文本
              }
            ]
          },
          {
            title: '重量(g)',
            key: 'weight',
            type: JVXETypes.input,
            width: '230px',
            defaultValue: '',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}' // 显示的文本
              }
            ]
          },
          {
            title: '拿货价(RMB)',
            key: 'purchasePrice',
            type: JVXETypes.input,
            width: '230px',
            defaultValue: '',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}' // 显示的文本
              }
            ]
          },
          {
            title: '货号',
            key: 'supplierItemNum',
            type: JVXETypes.input,
            width: '200px',
            defaultValue: '',
            placeholder: '请输入${title}',
            validateRules: [
              {
                message: '请输入${title}' // 显示的文本
              }
            ]
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          }
        ],
      },
      url: {
        supplierList: "/hzkj-product/product/productLibrary/supplier/list",
        generate: "/hzkj-product/product/productLibrary/sku/generate",
        getAttributeList: "/hzkj-product/product/productLibrary/sku/getAttributeList"
      }
    }
  },
  created(){
    this.getAttributeList();
  },
  watch: {
    model: {
      handler(){
        this.handleSkuList();
      }
    }
  },
  methods: {
    handleGenerate(){
      let that = this;
      this.$refs.form_.validate(valid => {
        if(valid){
          this.table.dataSource = [];
          let colorList=[], sizeList=[];
          if(this.skuModel.color && this.skuModel.color.length){
            let colorList_ = this.colorList.filter(item => {
              return this.skuModel.color.indexOf(item.id) > -1;
            })
            colorList_ = colorList_.map(item => {
              return {
                name: item.title,
                value: item.name
              }
            })
            colorList = [...colorList, ...colorList_];
          }
          if(this.skuModel.colorName){
            let colorList_ = this.skuModel.colorName.split(',') || [];
            colorList_ = colorList_.map(item => {
              return {
                value: item
              }
            })
            colorList = [...colorList, ...colorList_];
          }
          if(this.skuModel.sizeName){
            sizeList = this.skuModel.sizeName.split(',') || [];
            sizeList = sizeList.map(item => {
              return {
                value: item
              }
            })
          }else{
            // 排序
            let sizeList_attributeList = [];
            this.sizeList.forEach(item => {
              let titleList = item.attributeList.map(cur => cur.title);
              sizeList_attributeList = [...sizeList_attributeList, ...titleList];
            })
            let sizeList_ = this.skuModel.size.sort((a,b) => sizeList_attributeList.indexOf(a) - sizeList_attributeList.indexOf(b));
            sizeList = sizeList_.map(item => {
              return {
                value: item
              }
            })
          }
          let params = {
            colorList,
            sizeList,
            skuId: this.model.id
          }
          postAction(this.url.generate, params).then((res) => {
            if(res.success){
              this.$message.success(res.message);
              let dataSource = res.result || [];
              this.table.dataSource = dataSource.map(item => {
                return {
                  ...item,
                  supplierItemNum: this.model.supplierItemNum ? this.model.supplierItemNum : '',
                  color_: item.colorDesc ? `${item.colorDesc}/${item.color}` : item.color
                }
              })
              this.model.skuList = [...this.table.dataSource];
              this.skuValid = {
                validateStatus: '',
                message: ''
              }
              
              // 重量、拿货价
              this.$nextTick(() => {
                try{
                  let domList = document.querySelectorAll('.j-vxe-table-custom .vxe-table--main-wrapper .col--ellipsis')
                  domList.forEach(item => {
                    if(item.querySelector('.vxe-cell--title').innerHTML.indexOf('重量') > -1){
                      var parentElement = item.querySelector('.vxe-cell--title').parentNode; // 获取父元素
                      parentElement.innerHTML += `<div class="weight-input">
                                                    <span>差值</span>
                                                    <input id="weight-input-content" />
                                                  </div>`

                      document.getElementById('weight-input-content').addEventListener('blur', function(){
                        if(!that.model.weight){
                          that.$message.warning('请先设置基本信息中的重量！');
                          return;
                        }
                        // 去重
                        let dataSource = that.table.dataSource.filter((dataItem, dataIndex) => {
                          let currentDataIndex = that.table.dataSource.findIndex(curItem => dataItem.size === curItem.size);
                          return dataIndex === currentDataIndex;
                        })
                        let weight;
                        let length = dataSource.length;
                        that.table.dataSource = that.table.dataSource.map((itemDataSource, itemDataIndex) => {
                          if(itemDataIndex % length === 0){
                            weight = that.model.weight;
                          }
                          return {
                            ...itemDataSource,
                            weight: weight - (itemDataIndex % length) * this.value
                          }
                        })
                      })
                    }else if(item.querySelector('.vxe-cell--title').innerHTML.indexOf('拿货价') > -1){
                      var parentElement = item.querySelector('.vxe-cell--title').parentNode; // 获取父元素
                      parentElement.innerHTML += `<div class="price-input">
                                                    <input id="price-input-content" />
                                                    <span>填充</span>
                                                  </div>`

                      document.getElementById('price-input-content').addEventListener('blur', function(){
                        that.table.dataSource = that.table.dataSource.map(itemCur => {
                          return {
                            ...itemCur,
                            purchasePrice: this.value
                          }
                        })
                      })
                    }
                  })
                }catch(e){}
              })
            }else{
              this.$message.warning(res.message);
            }
          })
        }
      })
    },
    handleSkuList(){
      let dataSource = this.model.skuList || [];
      this.table.dataSource = dataSource.map(item => {
        return {
          ...item,
          color_: item.colorDesc ? `${item.colorDesc}/${item.color}` : item.color
        }
      })
    },
    getAttributeList(){
      getAction(this.url.getAttributeList).then((res) => {
        if(res.success){
          this.colorList = (res.result && res.result.color && res.result.color[0] && res.result.color[0].attributeList) || [];
          this.sizeList = (res.result && res.result.size) || {};
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    handleChange(type){
      if(type === 3){
        if(this.skuModel.sizeName){
          this.skuModel.sizeName = '';
        }
      }else if(type === 4){
        if(this.skuModel.size && this.skuModel.size.length){
          this.skuModel.size = [];
        }
      }
    },
    getSkuList(){
      return new Promise((resolve, reject) => {
        if(this.originModel.productType){
          resolve(true);
          return;
        }
        if(!(this.table.dataSource && this.table.dataSource.length)){
          this.skuValid = {
            validateStatus: 'error',
            message: '请生成SKU!'
          }
          resolve(false);
        }else{
          this.$refs.vTable.validateTable().then(errMap => {
            if(errMap){
              resolve(false)
            }else{
              this.model.skuList = this.$refs.vTable.getTableData();
              resolve(true);
            }
          })
        }
      })
    },
    handleDL(props) {
      // 调用删除方法
      props.target.removeRows(props.row)
    },
    colorValidator(rule, value, callback){
      if(!((this.skuModel.color && this.skuModel.color.length) || this.skuModel.colorName)){
        callback('请选择颜色！');
      }else{
        callback();
      }
    },
    sizeValidator(rule, value, callback){
      if(!((this.skuModel.size && this.skuModel.size.length) || this.skuModel.sizeName)){
        callback('请选择尺寸！');
      }else{
        callback();
      }
    }
  }
}
</script>

<style lang="less" scoped>
.ant-checkbox-group .ant-checkbox-wrapper{
  margin-left: 0;
}
/deep/.weight-input, /deep/.price-input{
  margin-left: 10px;
  width: 80px;
  white-space: nowrap;
  border: 1px solid #e8eaec;
  padding: 0 5px;
  border-radius: 4px;
  span{
    color: #aaa;
    font-size: 12px;
  }
  input{
    width: 35px;
    border: none;
    outline: none;
  }
}
/deep/.weight-input{
  input{
    border-left: 1px solid #e8eaec;
  }
}
/deep/.price-input{
  input{
    border-right: 1px solid #e8eaec;
  }
}
.color-setting{
  .ant-checkbox-wrapper{
    width: 108px;
    .color{
      display: inline-block;
      width: 26px;
      height: 26px;
      vertical-align: middle;
      margin-right: 8px;
      border: 1px solid #eee;
      border-radius: 4px;
    }
    .text{
      line-height: 26px;
    }
  }
}
</style>